package utilities;

import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


public class MapTools{
    public static void printMap(Map<String, Integer> map) {
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
    }
    
    public static void printMapDouble(Map<String, Double> map) {
        for (Map.Entry<String, Double> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " => " + twoDForm.format(entry.getValue()));
        }
    }
    
    public static TreeMap<String, Integer> getSortedMap(HashMap<String, Integer> map) {
        TreeMap<String, Integer> sortedMap = new TreeMap<>(new ValueComparator(map));
        sortedMap.putAll(map);

        return sortedMap;
    }
    
    public static TreeMap<String, Double> getSortedMapDouble(HashMap<String, Double> map) {
        TreeMap<String, Double> sortedMap = new TreeMap<>(new ValueComparatorDouble(map));
        sortedMap.putAll(map);

        return sortedMap;
    }
    
    private static class ValueComparator implements Comparator<String> {

        Map<String, Integer> base;

        public ValueComparator(Map<String, Integer> base) {
            this.base = base;
        }

        @Override
        public int compare(String a, String b) {
            if (base.get(a) >= base.get(b)) {
                return -1;
            } else {
                return 1;
            }
        }
    }
    
    private static class ValueComparatorDouble implements Comparator<String> {

        Map<String, Double> base;

        public ValueComparatorDouble(Map<String, Double> base) {
            this.base = base;
        }

        @Override
        public int compare(String a, String b) {
            if (base.get(a) >= base.get(b)) {
                return -1;
            } else {
                return 1;
            }
        }
    }
    
    public static DecimalFormat twoDForm = new DecimalFormat("#.##");
}
